<script>
export default {
  name: 'ChatView',
}
</script>
<script setup>
import { ref, onMounted, watch, provide, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { get_user_sessions, deleteSession } from '../../client/api/analysis'
import { getToken } from '../../client/api/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DataAnalysis, ChatDotRound, TrendCharts, Plus } from '@element-plus/icons-vue'
import FileUpload from '../../client/components/FileUpload.vue'
import HistorySidebar from '../../client/components/layout/HistorySidebar.vue'
import ChatAreaV1 from '../../client/components/layout/ChatAreaV1.vue'
// import InfoPanel from '../../client/components/layout/InfoPanel.vue'

// 获取当前路由
const route = useRoute()

// 当前选中的菜单
const currentMenu = ref('chat')

// 监听路由变化，同步更新 currentMenu
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/chat') {
      currentMenu.value = 'chat'
    } else if (newPath === '/datasets') {
      currentMenu.value = 'dataset'
    }
  },
  { immediate: true },
)

// 当前选中的对话 ID
const currentDialogId = ref(null)
// 提供currentDialogId给子组件使用
provide('currentDialogId', currentDialogId)
// ChatArea组件引用
const chatAreaRef = ref(null)
// 当前选中的数据集 ID
const currentDatasetId = ref(null)
// 控制是否显示上传界面
const showUploadPage = ref(false)
// 控制左侧面板展开/收起
const isLeftPanelCollapsed = ref(false)
// 控制右侧面板展开/收起
// const isRightPanelCollapsed = ref(false)

// 主题模式（true为夜间模式，false为白天模式）
const isDarkMode = ref(localStorage.getItem('theme') === 'light' ? false : true)

// 用户信息

// 在页面加载时检查登录状态
onMounted(async () => {
  // 首先检查URL参数中是否有token
  const urlToken = route.query.token
  if (urlToken) {
    // 设置token到本地存储，实现自动登录
    localStorage.setItem('token', urlToken)
    console.log('已从URL参数设置token:', urlToken)
  }

  const token = getToken()
  if (token) {
    // 获取用户历史会话列表
    await getUserSessions()
  }

  // 初始化主题
  // 从本地存储读取主题设置
  const savedTheme = localStorage.getItem('theme')
  if (savedTheme) {
    isDarkMode.value = savedTheme === 'dark'
  } else {
    // 如果没有保存的主题设置，默认使用暗色主题
    isDarkMode.value = true
    localStorage.setItem('theme', 'dark')
  }

  // 应用主题
  const htmlEl = document.documentElement
  if (isDarkMode.value) {
    htmlEl.classList.add('dark')
    document.body.setAttribute('class', 'el-dark-mode')
    // 添加Element Plus暗黑模式CSS类
    document.documentElement.style.setProperty('--el-color-primary', '#409EFF')
  } else {
    htmlEl.classList.remove('dark')
    document.body.removeAttribute('class')
    // 移除Element Plus暗黑模式CSS类
    document.documentElement.style.removeProperty('--el-color-primary')
  }
})

// 历史对话数据
const historyDialogs = ref([])

// 获取用户会话列表
const getUserSessions = async () => {
  try {
    const sessions = await get_user_sessions()
    if (sessions && Array.isArray(sessions)) {
      historyDialogs.value = sessions.map((session) => ({
        id: session.id,
        title: session.session_title || `对话${session.id}`,
        type: 'chat',
        starred: false,
        messages: session.messages || [],
        dataset_ids: session.dataset_ids,
      }))
      // 如果有历史会话，加载第一个会话
      if (historyDialogs.value.length > 0) {
        loadDialogMessages(historyDialogs.value[0])
        showUploadPage.value = false
      }
    } else {
      showUploadPage.value = true
    }
  } catch (error) {
    ElMessage.error('获取会话列表失败，请重试')
    // 检查是否是认证失败
    if (error.response?.status === 401 || error.response?.status === 403) {
      ElMessage.warning('请重新登录')
    } else {
      // 获取会话失败时也显示上传界面
      showUploadPage.value = true
    }
  }
}

// 加载对话消息 - 委托给ChatArea组件处理
const loadDialogMessages = async (dialog) => {
  currentDialogId.value = dialog.id
  // 处理dataset_ids字段：如果包含多个ID，取第一个
  if (dialog.dataset_ids && dialog.dataset_ids.trim()) {
    const datasetIds = dialog.dataset_ids.split(',').map(id => id.trim()).filter(id => id)
    currentDatasetId.value = datasetIds.length > 0 ? datasetIds[0] : null
  } else {
    currentDatasetId.value = null
  }
  // 隐藏上传界面
  showUploadPage.value = false

  // 使用nextTick确保ChatArea组件已经渲染
  await nextTick()

  if (chatAreaRef.value) {
    // 委托给ChatArea组件加载消息
    await chatAreaRef.value.loadDialogMessages(dialog)
  }
}

// 处理文件上传成功
const handleUploadSuccess = ({ historyDialogs: newHistoryDialogs }) => {
  // 更新会话列表
  historyDialogs.value = newHistoryDialogs

  // 如果有新的会话，自动选择最新的会话并获取分析方向
  if (historyDialogs.value.length > 0) {
    loadDialogMessages(historyDialogs.value[0])
  }

  // 隐藏上传页面
  showUploadPage.value = false
}

// 删除对话
const deleteDialog = async (dialog) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 调用删除接口
    await deleteSession(dialog.id)

    // 重新获取最新的会话列表
    const sessions = await get_user_sessions()
    if (sessions && Array.isArray(sessions)) {
      historyDialogs.value = sessions.map((session) => ({
        id: session.id,
        title: session.session_title || `对话${session.id}`,
        type: 'chat',
        starred: false,
        messages: session.messages || [],
        dataset_ids: session.dataset_ids,
      }))

      // 如果当前删除的是正在查看的会话，则切换到第一个可用会话
      if (currentDialogId.value === dialog.id) {
        if (historyDialogs.value.length > 0) {
          // 加载第一个会话
          loadDialogMessages(historyDialogs.value[0])
        } else {
          // 如果没有会话了，显示默认欢迎消息
          currentDialogId.value = null
        }
      }
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除对话失败，请重试')
    }
  }
}

// 创建新对话
const createNewChat = () => {
  showUploadPage.value = true
}

// 打开数据上传界面
const openDataUpload = () => {
  showUploadPage.value = true
}

// 刷新数据
const refreshData = async () => {
  try {
    ElMessage.info('正在刷新数据...')
    // 实际刷新逻辑
    if (currentDialogId.value) {
      await loadDialogMessages(historyDialogs.value.find((d) => d.id === currentDialogId.value))
      ElMessage.success('数据已刷新')
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新失败: ' + (error.message || '未知错误'))
  }
}
</script>

<template>
  <div class="app-container" :data-theme="isDarkMode ? 'dark' : 'light'">
    <!-- 使用 transition 组件实现平滑过渡 -->
    <transition name="page-transition" mode="out-in">
      <!-- 上传界面 -->
      <div v-if="showUploadPage" class="upload-page">
        <FileUpload
          @upload-success="handleUploadSuccess"
          @back="showUploadPage = false"
          :isDarkMode="isDarkMode"
        />
      </div>

      <!-- 主界面 -->
      <div v-else class="layout-container">
        <!-- 左侧历史会话区域 -->
        <HistorySidebar
          :dialogs="historyDialogs"
          :currentDialogId="currentDialogId"
          :isCollapsed="isLeftPanelCollapsed"
          @load-dialog="loadDialogMessages"
          @delete-dialog="deleteDialog"
          @create-new-chat="createNewChat"
        />

        <!-- 中央交互区 - 聊天界面或欢迎界面 -->
        <div v-show="currentMenu === 'chat'" class="chat-main-area">
          <!-- 无历史对话时的欢迎界面 -->
          <template v-if="historyDialogs.length === 0 && !showUploadPage">
            <transition name="page-transition" appear>
              <div class="empty-state glass-effect">
                <div class="empty-content">
                  <img
                    src="@/assets/logo.svg"
                    alt="析语Datatk"
                    class="empty-logo"
                    style="width: 380px; height: 140px; margin-bottom: 4px"
                  />
                  <div class="empty-features" style="margin-bottom: 32px; text-align: center">
                    <p class="feature-item" style="color: #606266; margin: 12px 0; font-size: 16px">
                      <el-icon style="margin-right: 8px; color: #409eff"><DataAnalysis /></el-icon>
                      智能分析数据，快速发现关键洞察
                    </p>
                    <p class="feature-item" style="color: #606266; margin: 12px 0; font-size: 16px">
                      <el-icon style="margin-right: 8px; color: #409eff"><ChatDotRound /></el-icon>
                      通过自然对话方式理解和探索数据
                    </p>
                    <p class="feature-item" style="color: #606266; margin: 12px 0; font-size: 16px">
                      <el-icon style="margin-right: 8px; color: #409eff"><TrendCharts /></el-icon>
                      提供专业的数据分析建议和可视化展示
                    </p>
                  </div>
                  <el-button
                    type="primary"
                    size="large"
                    style="width: 200px; height: 48px; font-size: 16px"
                    @click="createNewChat"
                  >
                    <el-icon style="margin-right: 8px"><Plus /></el-icon>开始新的对话
                  </el-button>
                </div>
              </div>
            </transition>
          </template>

          <!-- 有历史对话且已选中对话时显示ChatAreaV1组件 -->
          <ChatAreaV1
            v-else-if="historyDialogs.length > 0 && currentDialogId"
            ref="chatAreaRef"
            :isDarkMode="isDarkMode"
            :defaultDatasetId="currentDatasetId"
            :datasetFields="datasetFields"
            @start-new-chat="createNewChat"
            @create-new-dataset="openDataUpload"
            @refresh-data="refreshData"
          />

          <!-- 有历史对话但未选中对话时的提示界面 -->
          <template v-else-if="historyDialogs.length > 0 && !currentDialogId">
            <div class="empty-state glass-effect">
              <div class="empty-content">
                <el-icon style="font-size: 64px; color: #409eff; margin-bottom: 20px">
                  <ChatDotRound />
                </el-icon>
                <h3 style="margin-bottom: 16px; color: #303133">请选择一个对话</h3>
                <p style="color: #606266; margin-bottom: 24px">
                  从左侧历史对话列表中选择一个对话开始聊天，或者创建一个新的对话
                </p>
                <el-button type="primary" @click="createNewChat">
                  <el-icon style="margin-right: 8px"><Plus /></el-icon>创建新对话
                </el-button>
              </div>
            </div>
          </template>
        </div>

        <!-- 右侧信息流区域 ,暂时去除
        <InfoPanel
          v-if="currentMenu === 'chat' && chatAreaRef?.activeTab === 'chatTab' && currentDialogId"
          :isCollapsed="isRightPanelCollapsed"
          :currentDialogId="currentDialogId"
          @toggle-collapse="isRightPanelCollapsed = !isRightPanelCollapsed"
          @send-to-chat="handleSendDimensionToChat"
          @generate-report="handleReport"
          @toggle-dimension-lock="toggleDimensionLock"
        />-->
      </div>
    </transition>
  </div>
</template>

<style scoped>
/* 修改主布局样式为无间隙的左右布局 */
.layout-container {
  display: flex;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

/* 上传组件样式 */
.upload-page {
  flex: 1;
  width: 100%;
  height: 100%;
  overflow: auto;
  margin: 0;
  padding: 0;
}

/* 聊天主区域样式 */
.chat-main-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

/* 欢迎页样式 */
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  border-radius: 0;
  margin: 0;
}

.empty-content {
  max-width: 600px;
  padding: 40px;
  text-align: center;
  border-radius: var(--app-radius-base);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
}

:global(.dark-mode) .empty-content {
  background-color: rgba(40, 40, 40, 0.8);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.dark-mode :deep(.el-upload-dragger) {
  background: linear-gradient(145deg, rgba(45, 45, 45, 0.9), rgba(35, 35, 35, 0.8));
  border-color: rgba(255, 255, 255, 0.1);
  box-shadow:
    inset 0 2px 5px rgba(255, 255, 255, 0.05),
    0 2px 8px rgba(0, 0, 0, 0.2);
}

.dark-mode :deep(.el-upload-dragger:hover) {
  background: linear-gradient(145deg, rgba(50, 50, 50, 0.95), rgba(40, 40, 40, 0.85));
  border-color: var(--el-color-primary);
  box-shadow:
    inset 0 2px 5px rgba(255, 255, 255, 0.08),
    0 8px 15px rgba(0, 0, 0, 0.3);
}

/* 其他元素样式 */
.el-icon {
  margin-right: 0 !important;
}

.message-content {
  padding: var(--app-spacing-sm) var(--app-spacing-md) !important;
  line-height: var(--app-line-height-compact) !important;
}

.menu-item-actions {
  display: flex;
  gap: var(--app-spacing-xs);
  opacity: 0;
  transition: var(--app-transition-normal);
  align-items: center;
  margin-left: var(--app-spacing-sm);
}

/* 消息内数据表格样式 */
.message-data-tables {
  margin-top: var(--app-spacing-md);
  margin-bottom: var(--app-spacing-md);
  width: 100%;
}

.data-tabs {
  border-radius: var(--app-radius-sm);
  box-shadow: var(--app-shadow-sm);
}

.dark-mode .data-tabs {
  background-color: #252525;
  border-color: #363637;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 8px;
}

.table-title {
  font-size: 14px;
  color: #606266;
  flex: 1;
  font-weight: 500;
}

/* Tab内容区域暗黑模式样式 */
.dark-mode :deep(.el-tabs--border-card > .el-tabs__content) {
  background-color: #252525;
  color: #cfd3dc;
}

.dark-mode :deep(.el-tab-pane) {
  background-color: #252525;
}

.dark-mode :deep(.el-tabs__active-bar) {
  background-color: var(--el-color-primary);
}

:deep(.el-table--small) {
  font-size: var(--app-font-size-xs);
}

/* Tab相关样式 */
.main-tabs {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.main-tabs-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
  padding: 0;
}

:deep(.el-tabs__nav) {
  border-radius: var(--app-radius-lg) var(--app-radius-lg) 0 0;
}

:deep(.el-tab-pane) {
  height: 100%;
  overflow: hidden;
}

/* 数据面板样式 */
.data-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: var(--app-spacing-md);
  overflow: hidden;
}

.data-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--app-spacing-md);
}

.data-title {
  display: flex;
  flex-direction: column;
}

.data-title h3 {
  margin: 0;
  font-weight: 500;
  color: var(--app-text-primary);
}

.data-subtitle {
  font-size: var(--app-font-size-xs);
  color: var(--app-text-secondary);
  margin-top: 4px;
}

.data-empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: var(--app-text-secondary);
}

.data-panel-content {
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.pagination-container {
  padding: var(--app-spacing-md) 0;
  display: flex;
  justify-content: center;
}

/* 调整聊天容器样式适应Tab */
.chat-container {
  margin-top: 0;
  margin-bottom: 0;
  height: 100%;
  border-radius: 0;
}

/* 确保Tab内容区域撑满 */
:deep(.el-tabs__content) {
  overflow: auto !important;
}

:deep(.el-tab-pane) {
  overflow: auto !important;
}

/* 内容区Tab样式 */
.content-tabs-header {
  box-shadow: var(--app-shadow-hover);
  padding: var(--app-spacing-sm) var(--app-spacing-md);
}

.content-tabs {
  border: none;
}

:deep(.el-tabs--card > .el-tabs__header) {
  border-bottom: none;
  margin-bottom: 0;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
  border: none;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  border: none;
  margin-left: 15px;
  background: transparent;
  color: var(--app-text-regular);
  font-weight: 500;
  font-size: 15px;
  transition: all 0.3s;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  color: var(--el-color-primary);
  border-bottom: 2px solid var(--el-color-primary);
  font-weight: bold;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item:hover) {
  color: var(--el-color-primary-light-3);
}

.dark-mode :deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  color: var(--app-text-secondary);
  background: transparent;
  border-color: transparent;
}

.dark-mode :deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  color: var(--el-color-primary);
  border-bottom-color: var(--el-color-primary);
}

.dark-mode :deep(.el-tabs--card > .el-tabs__header .el-tabs__item:hover) {
  color: var(--el-color-primary-light-3);
}

/* 主内容容器 */
.main-content-container {
  height: 100%;
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* Tab内容样式 */
.tab-content {
  height: 100%;
  width: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

/* 确保Tab内容区域撑满 */
.chat-container,
.data-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.table-action-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #606266;
  background-color: rgba(0, 0, 0, 0.02);
}

.dark-mode .table-action-button {
  color: #aaa;
  background-color: rgba(255, 255, 255, 0.05);
}

.table-action-button:hover {
  color: var(--el-color-primary);
  background-color: rgba(var(--el-color-primary-rgb), 0.1);
  transform: scale(1.05);
}

.dark-mode .table-action-button:hover {
  background-color: rgba(var(--el-color-primary-rgb), 0.2);
}

/* 分析维度弹出框样式 */
.dimension-popover {
  padding: 8px;
}

.dimension-title {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 16px;
  color: var(--el-color-primary);
  border-bottom: 1px solid rgba(var(--el-color-primary-rgb), 0.2);
  padding-bottom: 8px;
}

.dimension-info {
  margin-bottom: 16px;
}

.dimension-item {
  margin-bottom: 8px;
  display: flex;
}

.dimension-item .label {
  font-weight: 500;
  color: var(--app-text-secondary);
  flex-shrink: 0;
  width: 80px;
}

.dimension-item .value {
  color: var(--app-text-primary);
  flex: 1;
}

.dimension-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 8px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

/* 锁定图标 */
.lock-icon {
  position: absolute;
  right: 6px;
  font-size: 16px;
  color: var(--app-text-secondary);
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  padding: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.lock-icon:hover {
  transform: scale(1.1);
  color: var(--el-color-primary);
  background-color: rgba(var(--el-color-primary-rgb), 0.1);
}

.lock-icon.locked {
  color: var(--el-color-danger);
}

.lock-icon.locked:hover {
  background-color: rgba(var(--el-color-danger-rgb), 0.1);
}

/* 分析结果按钮样式 */
.analysis-result-btn {
  width: 100%;
  margin-top: 8px;
  background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-light-3));
  border: none;
  font-weight: 500;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.analysis-result-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.3);
}

.dark-mode .analysis-result-btn {
  background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-dark-2));
}

.dark-mode .lock-icon {
  background-color: rgba(45, 45, 45, 0.9);
  color: #aaa;
}

.dark-mode .lock-icon:hover {
  background-color: rgba(var(--el-color-primary-rgb), 0.2);
}

.dark-mode .lock-icon.locked {
  color: var(--el-color-danger);
}

.dark-mode .lock-icon.locked:hover {
  background-color: rgba(var(--el-color-danger-rgb), 0.2);
}

/* 优化弹出框体验，减少悬停消失的问题 */
:deep(.el-popper) {
  margin-bottom: 0 !important;
  /* 增加过渡效果，提升用户体验 */
  transition:
    opacity 0.2s ease-in-out,
    transform 0.2s ease-in-out !important;
}

:deep(.el-popper[data-popper-placement^='top']) .el-popper__arrow {
  bottom: -4px !important;
}

/* 扩大弹出框的响应区域，减少消失概率 */
:deep(.el-popover) {
  padding: 12px !important;
}

/* 页面过渡动画 */
.page-transition-enter-active,
.page-transition-leave-active {
  transition: opacity 0.3s ease;
}

.page-transition-enter-from,
.page-transition-leave-to {
  opacity: 0;
}
</style>
